package com.zhan.utils.jwt;

import cn.com.chinatelecom.callcenter.utils.ClassUtils;
import cn.com.chinatelecom.callcenter.utils.model.CurrentUserInfo;
import com.alibaba.fastjson.JSONObject;
import com.zhan.utils.model.CurrentUserInfo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.jwt.Jwt;
import org.springframework.security.jwt.JwtHelper;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.Objects;

@Component
public class JwtUtils {

    @Autowired(required = false)
    private HttpServletRequest request;

    public JSONObject getClaims() {
        if (Objects.isNull(request)) {
            throw new NullPointerException("servlet 容器为空");
        }
        String authorization = request.getHeader("Authorization");
        if (StringUtils.isBlank(authorization)) {
            throw new NullPointerException("认证信息为空");
        }
        String token = StringUtils.substringAfter(authorization, "Bearer ");
        boolean present = ClassUtils.isPresent("org.springframework.security.jwt.JwtHelper");
        if (present) {
            Jwt decode = JwtHelper.decode(token);
            return JSONObject.parseObject(decode.getClaims());
        }
        return null;
    }

    public Long getUserId() {
        return getUserInfo().getId();
    }

    public CurrentUserInfo getUserInfo() {
        JSONObject claims = null;
        try {
            claims = getClaims();
        } catch (Throwable t) {
            System.err.println(t.getMessage());
        }
        CurrentUserInfo currentUserInfo = null;
        if (Objects.nonNull(claims)) {
            currentUserInfo = claims.getObject("user_info", CurrentUserInfo.class);
        }
        return currentUserInfo != null ? currentUserInfo : defaultUserInfo();
    }

    private CurrentUserInfo defaultUserInfo() {
        CurrentUserInfo currentUserInfo = new CurrentUserInfo();
        currentUserInfo.setId(111L);
        currentUserInfo.setEmpId(111L);
        currentUserInfo.setUsername("张三");
        currentUserInfo.setDepartmentId(111L);
        currentUserInfo.setDepartmentName("普综A区三班");
        currentUserInfo.setPhone("15088888888");
        currentUserInfo.setFullDepartmentName("10000运营部/普席位/运营二部普综A区/普综A区三班");
        currentUserInfo.setGeneralCode("111");
        currentUserInfo.setSnatchCode("q111");
        return currentUserInfo;
    }
}
